package com.example.opentiktok;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.annotation.Native;
import java.net.URLDecoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    public static final String ACTION_WECHAT_VIDEO_RECEIVER = "#Intent;package=com.zhiliaoapp.musically;scheme=https;S.browser_fallback_url=";
    WebView webview;
    TextView tv_open, tv_open_url;
    ImageView iv_close;
    EditText et_msg;
    String msg;
    String vmShortLink = "https://vm\\..*com/.*";
    String packageName = "com.ss.android.ugc.trill";
    String coverPattern = "(http.*://[^\\s]*)";
    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv_open = findViewById(R.id.tv_open);
        iv_close = findViewById(R.id.iv_close);
        tv_open_url = findViewById(R.id.tv_open_url);
        et_msg = findViewById(R.id.et_msg);
        webview = findViewById(R.id.webview);
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        //适应屏幕
        webview.getSettings().setUseWideViewPort(true);
        webview.getSettings().setLoadWithOverviewMode(true);
        //缩放
        //缩放开关u
        webview.getSettings().setSupportZoom(true);
        webview.setWebContentsDebuggingEnabled(true);
        webview.getSettings().setJavaScriptEnabled(true);// 支持javascript

        webview.addJavascriptInterface(new JavaObjectJsInterface(), "java_obj");
        tv_open_url.setText(Html.fromHtml("<a href='intent://vm.tiktok.com/ZSJpE7uPW/#Intent;scheme=https;package=com.zhiliaoapp.musically;S.browser_fallback_url=https://vm.tiktok.com/ZSJpE7uPW/;end'>打电话</a>"));
        tv_open_url.setMovementMethod(LinkMovementMethod.getInstance());
        et_msg.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                try {
                    if (null != s) {
                        String str = s.toString();

                        if (!"".equals(str)) {
                            //
                            getUri();

                        }

                    }

                } catch (Throwable throwable) {
                }
            }
        });
        tv_open.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String bUrl = msg;
                String iUrl = msg;
                if (isShortLink(bUrl, vmShortLink)) {
                    packageName = "com.zhiliaoapp.musically";
                } else if (isDouyinLisgk(bUrl)) {
                    packageName = "com.ss.android.ugc.aweme";
                } else {

                    packageName = "com.ss.android.ugc.trill";
                }

                String urlHost = getDyWorkUrl(iUrl);
                String uri = urlHost + "#Intent;scheme=https;package=" + packageName + ";S.browser_fallback_url=" + bUrl + ";end";

                intent(uri);
//                intent("https://vt.tiktok.com/");

            }
        });
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msg = "";
                et_msg.setText(msg);

            }
        });

        String url = "file:android_asset/ar-rEG.html";
        load(url);

    }

    /**
     * 是否是Tiktok链接
     *
     * @param str
     * @return
     */
    public boolean isDouyinLisgk(String str) {
        String videoUrl = null;
        Pattern r = Pattern.compile(".*https?://.*douyin\\.com/.*");
        Matcher m = r.matcher(str);
        LogUtil.d("video_url" + str);
        while (m.find()) {
            videoUrl = m.group();
            LogUtil.d("video_url_group" + m.group());
            break;
        }

        if (!"".equals(videoUrl) && null != videoUrl) {
            return true;
        } else {
            return false;

        }

    }

    private void getUri() {
        msg = et_msg.getText().toString().trim();

        String jsonTag = getJsonTag(msg, coverPattern);
        if (null != jsonTag&& !"".equals(jsonTag)) {
            msg = jsonTag;
        }
        if (null == msg || "".equals(msg)) {
            String newUrl = "javascript: f2('')";
            webview.loadUrl(newUrl);
        } else {
            String bUrl = msg;
            String iUrl = msg;
            if (isShortLink(bUrl, vmShortLink)) {
                packageName = "com.zhiliaoapp.musically";
            } else if (isDouyinLisgk(bUrl)) {
                packageName = "com.ss.android.ugc.aweme";
            } else {

                packageName = "com.ss.android.ugc.trill";
            }
            String urlHost = getDyWorkUrl(iUrl);
            String uri = urlHost + "#Intent;scheme=https;package=" + packageName + ";S.browser_fallback_url=" + bUrl + ";end";
//            String uri = urlHost+ "#Intent;scheme=https;package=com.zhiliaoapp.musically;S.browser_fallback_url=" + bUrl + ";end";
            String newUrl = "javascript: f2('" + uri + "')";
            webview.loadUrl(newUrl);
        }


    }

    private void injectJsSample2() {
        String tmp2 = "javascript: function f2() {  var links = document.getElementsByClassName('a_intent')[0];  window.java_obj.jsMethod(links.getAttribute(\"href\"));   }";
        // 先注入1
        webview.loadUrl(tmp2);

    }

    /**
     * 逻辑处理
     *
     * @author linzewu
     */
    public class JavaObjectJsInterface {

        @JavascriptInterface // 要加这个注解，不然调用不到
        public void jsMethod(String paramFromJS) {
            //Log.i("CDH", paramFromJS);
            System.out.println("js返回结果" + paramFromJS);//处理返回的结果
        }

        @JavascriptInterface // 要加这个注解，不然调用不到
        public void onHtml(String html) {
            Log.d("", "html_info  " + html);

        }

    }

    public static String getDyWorkUrl(String url) {
        String urlStr = url.replace("https", "intent");

        return urlStr;
    }
    public String getJsonTag(String html, String patternSrt) {
        String videoUrl = null;


        Pattern r = Pattern.compile(patternSrt);
        Matcher m = r.matcher(html);
        while (m.find()) {
            videoUrl = m.group(0);
            break;
        }

        return videoUrl;
    }

    private void load(String url) {

        if (url != null) {
            try {
                webview.loadUrl(URLDecoder.decode(url, "UTF-8"));
            } catch (Throwable e) {
                webview.loadUrl(url);

            }
        }
    }

    private void intent(String uri) {
        Log.d("intent", "uri : " + uri);

        Intent intent1 = new Intent();
        intent1.setData(Uri.parse(uri));
        this.startActivity(intent1);
    }

    public void openUrl(Activity activity, String videoUrl) {
        Intent intent = new Intent(videoUrl);
        activity.startActivity(intent);
    }

    /**
     * 判断是否   https://vm. 或 https://vt. 开头的域名
     * 龚绪凡 7-21 09:07:01
     *
     * @param str
     * @param regex
     * @return
     */
    public boolean isShortLink(String str, String regex) {
        String videoUrl = null;
        Pattern r = Pattern.compile(regex);
        Matcher m = r.matcher(str);
        Log.d("", "isShortLink" + str);
        while (m.find()) {
            videoUrl = m.group();
            Log.d("", "video_url_group" + m.group());
            break;
        }

        if (null != videoUrl && !"".equals(videoUrl)) {
            return true;
        } else {
            return false;

        }

    }

}